<template>
 <el-dialog :title="'导入'+configName" v-model="dialogVisible" width="800px" append-to-body>
   <div v-if="configs">
     请选择导入内容：
     <el-select size="small" clearable style="width: 300px;margin-right: 20px;" v-model="configKeyTemp" placeholder="请选择">
       <el-option v-for="item in configs" :label="item.name" :value="item.key"  :key="item.key" />
     </el-select>
     <el-button  size="small"  type="primary" @click="getConfig(configKeyTemp)">确定</el-button>
   </div>
  <div v-else>
    <el-timeline>
        <el-timeline-item
          v-for="(item, index) in resList"
           :color="colors[item.errorType]"
          :key="index">
           {{resTypes[item.errorType]}}
           <div v-if="item.errorType!=='NO_ERROR'">
   
             <div v-if="index==resList.length-1">
              <!-- <el-button type="primary" size="small" style="margin-right:10px;"
                @click="$refs.myExcel.open(item.url,configName)">在线编辑</el-button>
               或 -->
              请 <el-button link type="primary" @click="downFile(item.url)">下载文件</el-button> 进行编辑后继续上传
             </div>
             <el-button link v-else type="primary" disabled>已处理</el-button>
           </div>
        </el-timeline-item>
      </el-timeline>
      <div v-if="!resList.length||resList[resList.length-1].errorType!=='NO_ERROR'">
        <el-upload
          style="margin:0 200px;"
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :data="{ cacheId:resList.length?resList[resList.length-1].cacheId:''}"
          :headers="upload.headers"
          :action="upload.url + configKey"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-change="()=>{upload.showUploadBtn=true}"
          :on-remove="()=>{upload.showUploadBtn=false}"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
             @click.stop="importTemplate">下载模板</el-link>
          </div>
        </el-upload>
        <el-button type="primary" v-if="upload.showUploadBtn" @click="uploadRef.submit()" style="margin:10px 0 0 344px;">上 传</el-button>
    </div>
    <!-- <my-excel ref="myExcel"/> -->
  </div>
 
 
 
  <template #footer>
    <span class="dialog-footer">
  	   <el-button @click="dialogVisible = false">关 闭</el-button>
    </span>
  </template>
 </el-dialog>
</template>

<script setup name="ImportFile">
// import myExcel from './excel.vue'
import {
  getInfoByKey
} from "@/api/tool/importExport";
import { getToken } from "@/utils/auth";
import { parseTime } from "@/utils/ruoyi";
import { ElMessage } from 'element-plus'

const {proxy} = getCurrentInstance();
const VITE_APP_BASE_API=import.meta.env.VITE_APP_BASE_API

const uploadRef=$ref(null),
	  configs=$ref(null),
	  configKeyTemp=$ref(''),
	  dialogVisible=$ref(false),
	  configKey=$ref(''),
	  configName=$ref(''),
	  upload=$ref({
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer "+getToken()},
        // 上传的地址
        url: VITE_APP_BASE_API + "/openform/ImportExport/importData/",
        showUploadBtn:false,
      }),
	  colors=$ref({
        NO_ERROR:'#67C23A',
        HEAD_ERROR:'#E6A23C',
        DATA_FORMAT_ERROR:'#F56C6C',
        COMPLEX_DATA_ERROR:'#F56C6C',
      }),
	  resTypes=$ref({
        NO_ERROR:'导入成功，请刷新列表',
        HEAD_ERROR:'表头出错',
        DATA_FORMAT_ERROR:'数据格式错误',
        COMPLEX_DATA_ERROR:'数据导入错误',
      }),
	  resList=$ref([
        {errorType:'NO_ERROR'},
        {errorType:'HEAD_ERROR'},
        {errorType:'DATA_FORMAT_ERROR'},
        {errorType:'COMPLEX_DATA_ERROR'},
      ]);

	function open(list){
      resList=[]
      configName=''
      upload.showUploadBtn=false
      if(list.length==1){
        getConfig(list[0].key)
        configName=list[0].name
      }else{
        configs=list
        dialogVisible=true
      }
    }	
	function getConfig(key){
	  getInfoByKey(key).then(res=>{
	    if(res.data){
	      configKey=key
	      configName=res.data.configName
	      configs=null
	      dialogVisible=true
	    }
	  })
	}
	// 文件上传中处理
	function handleFileUploadProgress(event, file, fileList) {
	  upload.isUploading = true;
	}
	// 文件上传成功处理
	function handleFileSuccess(response, file, fileList) {
	  uploadRef.clearFiles()
	  upload.isUploading = false;
	  if(response.code!=200){
	    ElMessage({
			message: '上传失败，请重试',
			type: 'error',
			showClose: true,
			duration: 2000
		})
	    return
	  }
	
	  response.data.url=VITE_APP_BASE_API+response.data.url
	  resList.push(response.data)
	
	  setTimeout(()=>{
	    upload.showUploadBtn=false
	  },100)
	}
	/** 下载模板操作 */
	function importTemplate() {
	  proxy.download('openform/ImportExport/downloadTemplate/'+configKey, {
	  }, `${configName}_${parseTime(new Date(),'{y}{m}{d}{h}{i}{s}')}.xlsx`)
	}
	//下载出错文件
	function downFile(url){
	    const a = document.createElement('a');
	    a.href = url;
	    a.download =  `${configName}_${parseTime(new Date(),'{y}{m}{d}{h}{i}{s}')}.xlsx`;
	    document.body.appendChild(a);
	    a.click();
	    document.body.removeChild(a);
	    URL.revokeObjectURL(url);
	}
	defineExpose({
		open
	})
</script>
